const path = require('path');
const webpack = require('webpack');
const glob = require('glob-all');
const config = require('./prod.conf');
const merge = require('webpack-merge');
const utils = require('../component/utils');
const _ = require('lodash');
const ExtractTextPlugin = require('extract-text-webpack-plugin');
const OptimizeCSSPlugin = require('optimize-css-assets-webpack-plugin');
const CompressionWebpackPlugin = require('compression-webpack-plugin');

const RootPath = path.resolve(__dirname, '..');

module.exports = function ({subProjectName, libName}) {
    const scriptConfigFiles = glob.sync(`src/${subProjectName}/libs/${libName}/*.js`, {
        cwd: RootPath
    });
    const scripts = _.chain(scriptConfigFiles).map(function (filename) {
        return path.resolve(RootPath, filename);
    }).flatten().value();
    const entry = {};
    entry[libName] = scripts;

    const manifestFiles = glob.sync(`src/${subProjectName}/libs/${libName}/manifests/*.json`, {
        cwd: RootPath,
    });

    const manifestPlugins = _.map(manifestFiles, function (filename) {
        const pluginConfig = {
            context: RootPath,
            manifest: require(path.resolve(RootPath, filename)),
        };
        return new webpack.DllReferencePlugin(pluginConfig);
    });

    const libAssetsRoot = path.resolve(config.assetsRoot, subProjectName, 'libs', libName);
    const baseWebpackConfig = {
        entry: entry,
        output: {
            path:libAssetsRoot,
            filename: '[name].[chunkhash].js',
            publicPath: `/${subProjectName}/libs/${libName}/`,
            library: '[name]_[chunkhash]',
        },
        devtool: '#source-map',
        resolve: {
            extensions: ['.js', '.vue', '.json'],
            modules: [
                path.resolve(__dirname, '../src'),
                path.resolve(__dirname, '../node_modules')
            ],
            alias: {
                //-------以下不能改变--------
                'vue$': 'vue/dist/vue.esm.js',
                '$PEDESTAL': path.resolve(__dirname, '../src/pedestal/libs'),
                '$USER': path.resolve(__dirname, '../src/user/libs'),
                //---------------
            }
        },
        module: {
            rules: [
                {
                    test: /\.vue$/,
                    loader: 'vue-loader',
                    exclude: new RegExp('/node_modules/'),
                    options: {
                        loaders: utils.cssLoaders({
                            sourceMap: config.sourceMap,
                            extract: config.extract
                        }),
                        postcss: [
                            require('autoprefixer')({
                                browsers: ['last 2 versions']
                            })
                        ]
                    }
                },
                {
                    test: /\.js$/,
                    loader: 'babel-loader',
                    exclude: new RegExp('/node_modules/'),
                    include: [path.resolve(RootPath, 'src', subProjectName, 'libs', libName)]
                },
                {
                    test: /\.(png|jpe?g|gif|svg)(\?.*)?$/,
                    loader: 'url-loader',
                    query: {
                        limit: 10000,
                        name: path.join(libAssetsRoot, config.assetsSubDirectory, 'img/[name].[hash:7].[ext]')
                    }
                },
                {
                    test: /\.(woff2?|eot|ttf|otf)(\?.*)?$/,
                    loader: 'url-loader',
                    query: {
                        limit: 10000,
                        name: path.join(libAssetsRoot, config.assetsSubDirectory, 'fonts/[name].[hash:7].[ext]')
                    }
                },
                {
                    test: /\.scss$/,
                    loader: 'style!css!sass'
                }
            ]
        }
    };

    return merge(baseWebpackConfig, {
        module: {
            rules: utils.styleLoaders({
                sourceMap: true,
                extract: true
            })
        },
        plugins: [
            // http://vuejs.github.io/vue-loader/en/workflow/production.html
            new webpack.DefinePlugin({
                'process.env': JSON.stringify(process.env.NODE_ENV)
            }),
        ].concat(manifestPlugins).concat([
            new webpack.ContextReplacementPlugin(/moment[\/\\]locale$/, /en-|zh-/),
            new webpack.optimize.UglifyJsPlugin({
                compress: {
                    warnings: false
                },
                sourceMap: true
            }),
            // extract css into its own file
            new ExtractTextPlugin({
                filename: utils.assetsPath('css/[name].[contenthash].css', config.assetsSubDirectory)
            }),
            // Compress extracted CSS. We are using this plugin so that possible
            // duplicated CSS from different components can be deduped.
            new OptimizeCSSPlugin(),
            // generate dist index.html with correct asset hash for caching.
            // you can customize output by editing /index.html
            // see https://github.com/ampedandwired/html-webpack-plugin
            // split vendor js into its own file
            new CompressionWebpackPlugin({
                asset: '[path].gz[query]',
                algorithm: 'gzip',
                test: new RegExp('[.](js|css)$'),
                threshold: 10240,
                minRatio: 0.8
            }),
            new webpack.DllPlugin({
                path: path.join(config.assetsRoot , subProjectName, 'libs', libName, '[name].[chunkhash].json'),
                name: '[name]_[chunkhash]',
                context: RootPath,
            }),
        ])
    });
};

